package com.zsk.tool.file;

import java.io.Closeable;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 
 * @author keke
 * @date 2020/11/14
 */
public class BinaryFileUtil {
    public static boolean writeFileWithBinary(String str, String path) {
        return writeFileWithBinary(str.getBytes(), path);
    }

    public static boolean writeFileWithBinary(byte[] bytes, String path) {
        DataOutputStream dos = null;
        try {
            File dir = new File(path).getParentFile();
            if (!dir.isDirectory()) {
                dir.mkdirs();
            }
            int len = bytes.length;
            for (int i = 0; i < len; i++) {
                bytes[i] = (byte)((int)bytes[i]);
            }
            dos = new DataOutputStream(new FileOutputStream(path));
            dos.write(bytes);
            dos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(dos);
        }
        return false;
    }

    public static void readFileWithBinary(String path) {
        DataInputStream in = null;
        try {

            in = new DataInputStream(new FileInputStream(path));
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = in.read(b)) > 0) {
                for (int i = 0; i < len; i++) {
                    System.out.print((char)b[i] + " ");
                }
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(in);
        }
    }

    public static void close(Closeable io) {
        if (io != null) {
            try {
                io.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        byte[] b = new byte[128];
        for (int i = 0; i < 128; i++) {
            b[i] = (byte)i;
        }
        writeFileWithBinary(b, "C:\\Users\\admin\\Desktop\\test.db");
        readFileWithBinary("C:\\Users\\admin\\Desktop\\test.db");
    }

}
